<?php
/**
 * @package quizzes
 * @author Andrew Meredith <andymeredith@gmail.com>
 */
namespace PhpQuizzes;

/**
 * This class is a basic quiz object
 * Quizzes may be created by an administrator. They can cantain a number of different
 * personalities and questions.
 */
class Quiz {
	/** @property int $_id The unique identifier of this quiz object in the database */
	private $_id;
	
	/** @property string $_title The human-readable name of the quiz - used in the admin interface and the front-facing application */
	private $_title;
	
	/** @property array $_questions An array of questions that belong to this Quiz */
	private $_questions;
	
	/** @property array $_inactive_questions An array of questions to purge upon save */
	private $_inactive_questions;
	
	/** @property PhpQuizzes\Database\QuizSerializer An object responsible for persisting Quizzes */
	private $_serializer;
	
	public function Quiz() {
		$this->_serializer = PhpQuizzes\Database\QuizSerializer::instance();
	}
	
	public function getId() {
		return $this->_id;
	}
	
	public function setId( $id ) {
		if (is_int( $id )) {
			$this->_id = $id;
		} else {
			throw new InvalidArgumentException("Invalid ID supplied. Expected an integer, but got '$id'");
		}
	}
	
	public function getTitle() {
		return $this->_title;
	}
	
	public function setTitle( $title ) {
		$this->_title = $title;
	}
	
	/**
	 * Adds a Question to this Quiz
	 *
	 * When the Quiz is saved, each associated Question will be saved as well
	 *
	 * @param Question $q
	 */
	public function addQuestion(Question $q) {
		foreach ($this->_questions as $question) {
			if ($q == $question) return;
		}
		$this->_questions[] = $q;
	}
	
	/**
	 * Queues a question for removal upon save
	 *
	 * @param Question $q The question to remove
	 * @return void
	 */
	public function removeQuestion(Question $q) {
		foreach ($this->_questions as $index => &$question) {
			if ($q == $question) {
				unset($this->_questions[$index]);
				$this->_inactive_questions[] = $q;
				return;
			}
		}
	}
	
// PERSISTENCE METHODS

	/**
	 * Saves the current quiz to the database
	 *
	 * @return int|boolean Upon success, the id of the Quiz saved; upon failure, Boolean <i>false</i>
	 */
	public function save() {
		return $this->_serializer->save($this);
	}
	
	/**
	 * Saves the current quiz to the database
	 *
	 * @return boolean True upon success, false upon failure
	 */
	public function delete() {
		return $this->_serializer->destroy($this);
	}
}